import Vue from 'vue'
import VueRouter from 'vue-router'
import {MessageBox} from "element-ui"

import Login from '../views/Login.vue'
import NotFound from '../views/NotFound'
import store from '../store'
import axios from 'axios'
import About from '../views/user/About.vue'
import UserIndex from '../views/user/UserIndex.vue'
import AddressList from '../views/user/AddressList.vue'
import CoffeeOrigin from '../views/user/CoffeeOrigin.vue'
import AllCoffees from '../views/user/AllCoffees.vue'
import Merchandise from '../views/user/Merchandise.vue'
import Cart from '../views/user/Cart.vue'
import ProductDetail from '../views/user/ProductDetail.vue'
import ProductReview from '../views/user/ProductReview.vue'
import Pay from '../views/user/Pay.vue'
import Order from '../views/user/Order.vue'
import Register from '../views/Register'
import LayoutWithHeader from '../components/LayoutWithHeader'
import LayoutBlank from '../components/LayoutBlank'
import AddAddress from "../views/user/AddAddress.vue";
import EditAddress from "../views/user/EditAddress.vue";
import MerchandiseReview from "@/views/user/MerchandiseReview.vue";
import MerchandiseProductDetail from "../views/user/MerchandiseProductDetail.vue";
import MerchandiseSearchResult from "../views/user/MerchandiseSearchResult.vue";
import CoffeeSearchResult from "../views/user/CoffeeSearchResult.vue";


import Editmy from "../views/user/Editmy.vue"

Vue.use(VueRouter)

const routes = [


  // 2. 嵌套路由（基于AdminLayout）
  {
    path: '/admin',
    name: 'AdminLayout',
    component: () => import('@/components/admin/AdminLayout.vue'), // 管理员布局
    meta: { requiresAuth: true, roles: ['admin'] }, // 仅管理员可访问
    redirect: '/admin/dashboard', // 默认跳转到控制台
    children: [
      // 通用页面
      {
        name: 'AdminDashboard',
        path: 'dashboard',
        component: () => import('@/views/admin/Dashboard.vue'),
        meta: { title: '控制台', icon: 'el-icon-s-home' } // 侧边栏图标+标题
      },
      {
        name: 'AdminUserCenter',
        path: 'user-center',
        component: () => import('@/views/user/UserCenter.vue'),
        meta: { title: '个人中心', icon: 'el-icon-user' }
      },

      // 用户管理模块
      {
        name: 'AdminUserList',
        path: 'user/list',
        component: () => import('@/views/admin/user/UserList.vue'),
        meta: { title: '用户列表',
          icon: 'el-icon-user',

        }
      },

      // 商品管理模块
      {
        name: 'AdminCoffeeProductList',
        path: 'coffee-product/list',
        component: () => import('@/views/admin/product/CoffeeProductList.vue'),
        meta: { title: '咖啡商品管理', icon: 'el-icon-goods' }
      },
        {
        name: 'AdminMerchandiseProductList',
        path: 'merchandise-product/list',
        component: () => import('@/views/admin/product/MerchandiseProductList.vue'),
        meta: { title: '周边商品管理', icon: 'el-icon-goods' }
      },
      {
        name: 'AdminMerchandiseCategoryList',
        path: 'merchandise-product/category',
        component: () => import('@/views/admin/product/MerchandiseCategory.vue'),
        meta: { title: '周边商品分类管理', icon: 'el-icon-menu' }
      },
        {
        name: 'AdminCoffeeCategoryList',
        path: 'coffee-product/category',
        component: () => import('@/views/admin/product/CoffeeCategory.vue'),
        meta: { title: '咖啡分类管理', icon: 'el-icon-menu' }
      },

      // 订单管理模块
      {
        name: 'AdminOrderList',
        path: 'order/list',
        component: () => import('@/views/admin/order/OrderList.vue'),
        meta: { title: '订单列表', icon: 'el-icon-document' }
      },
      {
        name: 'AdminOrderDetail',
        path: 'order/detail/:id',
        component: () => import('@/views/admin/order/OrderDetail.vue'),
        meta: { title: '订单详情', hidden: true }
      },
      {
        name: 'AdminOrderEdit',
        path: 'order/edit/:id',
        component: () => import('@/views/admin/order/OrderEdit.vue'),
        meta: { title: '修改订单状态', hidden: true }
      },
      {
        name: 'Review',
        path: 'product/Review',
        component: () => import('@/views/admin/product/ProductReview.vue'),
        meta: { title: '评论管理', icon: 'el-icon-s-home' } // 侧边栏图标+标题
      },
    ]
  },

  {
    path: '/',
    component: LayoutWithHeader,
    children: [
      {path: '', redirect: '/user-index'},
      {
        path: '/user-index',
        name: 'UserIndex',
        component: UserIndex,
        meta:
            {allowVisitor: true},
      },
      {
        path: '/about',
        name: 'About',
        component: About,
        meta: {allowVisitor: true}
      },
      {
        path: '/addresslist',
        name: 'AddressList',
        component: AddressList,
        meta: {requiresAuth: true,
          roles: ['customer', 'admin'],
        }
      },
      {
        path: 'coffee-search-result',
        name: 'CoffeeSearchResult',
        component: CoffeeSearchResult,
        meta: {allowVisitor: true}
      },
      // 周边搜索结果页
      {
        path: 'merchandise-search-result',
        name: 'MerchandiseSearchResult',
        component: MerchandiseSearchResult,
        meta: {allowVisitor: true}
      },
      {
        path: '/pay',
        name: 'Pay',
        component: Pay,
        meta: { requiresAuth: true, roles: ['customer','admin'] }
      },
      {
        path: '/editmy',
        name: 'Editmy',
        component: Editmy,
        meta: { requiresAuth: true, roles: ['customer','admin'] }
      },
      {
        path:'/addaddress',
        name:'Addaddress',
        component:AddAddress,
        meta: {
          requiresAuth: true,
          roles: ['customer','admin']
        }
      },
      {
        path:'/order',
        name: 'order',
        component:Order,
        meta: { requiresAuth: true, roles: ['customer','admin'] }
      },
      {
        path:'/editaddress',
        name:'EditAddress',
        component:EditAddress,
        meta: { requiresAuth: true, roles: ['customer','admin'] }
      },
      {
        path: '/coffee-origin',
        name: 'CoffeeOrigin',
        component: CoffeeOrigin,
        meta: {allowVisitor: true}
      },
      {
        path: '/all-coffees',
        name: 'AllCoffees',
        component: AllCoffees,
        meta: {allowVisitor: true}
      },
      {
        name: 'Merchandise',
        path: '/merchandise',
        component: Merchandise,
        meta: {allowVisitor: true}},
      {
        path: '/favorite',
        name: 'Favorite',
        component: () => import('@/views/user/Favorite.vue'),
        meta: { requiresAuth: true, roles: ['customer','admin'] }
      },
      {
        path: '/cart',
        name: 'Cart',
        component: Cart,
        meta: { requiresAuth: true, roles: ['customer','admin'] }
      },
      {
        path: '/productdetail',
        name: 'ProductDetail',
        component: ProductDetail,
        meta: {
        allowVisitor: true
        }
      },
      {
        path:'/merchandiseproductdetail/:id',
        name:'MerchandiseProductDetail',
        component:MerchandiseProductDetail,
        meta: {allowVisitor: true}
      }

    ]
  },

  {
    path: '/user-center',
    name: 'UserCenter',
    component: () => import('../views/user/UserCenter.vue'),
    meta: { requiresAuth: true, roles: ['customer','admin'] }
  },

  {
    path: '/review',
    name: 'ProductReview',
    component: ProductReview,
    meta: { requiresAuth: true, roles: ['customer','admin'] }
  },
  {
    path: '/review',
    name: 'MerchandiseReview',
    component:MerchandiseReview,
    meta: { requiresAuth: true, roles: ['customer','admin'] }
  },

  {
    name: 'Login',
    path: '/login',
    component: Login
  },
  {
    path: '/register',
    name: 'Register',
    component: Register
  },
  {
    name: 'NotFound',
    path: '/notfound',
    component: NotFound
  },
  {
    path: '*', // 匹配所有未定义的路径
    redirect: '/notfound' // 重定向到现有 NotFound 页面
  }
]

const router = new VueRouter({
  mode: 'history',
  routes
})



router.beforeEach(async (to, from, next) => {

    console.log('路由守卫触发，目标页面：', to.path)
  console.log('当前 Token：', localStorage.getItem('token'))
  console.log('游客状态：', store.getters['user/isVisitor'])
  console.log('用户信息：', store.state.profile)

  // 1. 先定义所有需要的状态和白名单（保持原逻辑变量）
  const isVisitor = store.getters['user/isVisitor'] || false;
  const whiteList = ['/login', '/register'];
  const token = localStorage.getItem('token');

  // 2. 保留原「游客在白名单页面」的逻辑：跳登录/注册时直接放行
  if (isVisitor && whiteList.includes(to.path)) {
    return next();
  }

  // 3. 保留原「游客非白名单页面」的逻辑：判断是否允许游客访问
  if (isVisitor) {
    if (to.meta.allowVisitor) {
      return next();
    } else {
      store.commit('user/SET_REDIRECT_PATH', to.path);
      return MessageBox.confirm(
        '您还暂未登录，无法访问该功能，是否前往登录？',
        '提示',
        { center: true, type: 'warning' }
      ).then(() => next('/login'))
        .catch(() => next(from.path || '/user-index'));
    }
  }

  // 4. 保留原「根路径（/）」的逻辑：根据token和角色跳转
  if (to.path === '/') {
    if (!token) return next('/login');
    if (!store.state.profile) {
      try {
        await store.dispatch('fetchProfile');
      } catch {
        store.dispatch('logout');
        return next('/login');
      }
    }
    const role = store.state.profile.role;
    return role === 'admin' ? next('/admin/dashboard') : next('/user-index');
  }

  // 5. 保留原「白名单页面（非游客）」的逻辑：直接放行
  if (whiteList.includes(to.path)) {
    return next();
  }

  // 6. 保留原「未登录拦截、拉取profile、角色权限校验」的核心逻辑
  if (!token) {
    return to.path === '/login' ? next() : next('/login');
  }

  if (!store.state.profile) {
    try {
      await store.dispatch('fetchProfile');
    } catch {
      store.dispatch('logout');
      return next('/login');
    }
  }

  // 保留原「合并所有父路由roles并校验」的逻辑
  const allRoles = to.matched.reduce((roles, route) => {
    return [...roles, ...(route.meta.roles || [])];
  }, []);

  if (allRoles.length > 0) {
    const userRole = store.state.profile.role;
    if (!allRoles.includes(userRole)) {
      return userRole === 'admin' ? next('/admin/dashboard') : next('/user-index');
    }
  }

  // 7. 所有校验通过，正常放行（原逻辑结尾）
  next();
})

const menuToRoute = childMenu => {
  if (!childMenu.component) return null
  return {
    name: childMenu.name,
    path: childMenu.path,
    meta: { icon: childMenu.icon, title: childMenu.title },
    component: () => import(`@/views/${childMenu.component}.vue`)
  }
}

export default router